﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AmuTools.Tencent
{
    public class TencentOCR
    {
        #region 属性
        public string AppId { get; private set; }
        public string SecretId { get; private set; }
        public string SecretKey { get; private set; }
        #endregion

        #region 构造函数
        public TencentOCR(string appId, string secretId, string secretKey)
        {
            AppId = appId;
            SecretId = secretId;
            SecretKey = secretKey;
        }
        #endregion

        #region 认证与请求
        private string GetAuthorization()
        {
            long now = GetCurrentTimeStamp();
            long expired = 86400;
            int rdm = GetRandom();

            string temp = string.Format("a={0}&k={1}&t={2}&e={3}&r={4}", 
                AppId, SecretId, now, now + expired, rdm);

            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(SecretKey);
            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(temp);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            string result = Convert.ToBase64String(hashBytes.Concat(dataBuffer).ToArray());
            
            return result;
        }

        private long GetCurrentTimeStamp()
        {
            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
            return ((long)ts.TotalMilliseconds) / 1000;
        }

        private int GetRandom()
        {
            Random random = new Random();
            return random.Next();
        }

        private string Request(string url, string base64mage)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.Host = "recognition.image.myqcloud.com";
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", GetAuthorization());

            Stream reqStream = webRequest.GetRequestStream();
            var o = new { appid = AppId, image = base64mage };
            string json = JsonConvert.SerializeObject(o);
            byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
            reqStream.Write(jsonBytes, 0, jsonBytes.Length);
            reqStream.Close();

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
            return sr.ReadToEnd();
        }
        #endregion

        #region 功能
        /// <summary>
        /// 通用印刷体识别
        /// </summary>
        /// <param name="base64Image"></param>
        /// <returns></returns>
        public GeneralResponse General(string base64Image)
        {
            string httpUrl = "http://recognition.image.myqcloud.com/ocr/general";

            string responseStr = Request(httpUrl, base64Image);
            GeneralResponse response = JsonConvert.DeserializeObject<GeneralResponse>(responseStr);

            return response;
        }
        #endregion

        #region
        public static string ImageToBase64(string imageFileName)
        {
                Bitmap bmp = new Bitmap(imageFileName);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();

                return Convert.ToBase64String(arr);
        }
        #endregion
    }

    public class ResponseBase
    {
        public int code { get; set; }
        public string message { get; set; }
        public ResponseData data { get; set; }
    }

    public class GeneralResponse: ResponseBase
    {

    }

    public class ResponseData
    {
        public string session_id { get; set; }
        public DataItem[] items { get; set; }
    }

    public class DataItem
    {
        public string itemstring { get; set; }
        public ItemCoord itemcoord { get; set; }
        public ItemWord[] words { get; set; }
    }

    public class ItemCoord
    {
        public int x { get; set; }
        public int y { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }

    public class ItemWord
    {
        public string character { get; set; }
        public float confidence { get; set; }
    }
}
